package com.dxg.config;

import com.dxg.provider.filter.SmsAuthenticationProcessingFilter;
import com.dxg.provider.handler.SmsAuthenticationFailureHandler;
import com.dxg.provider.handler.SmsAuthenticationSuccessHandler;
import javax.annotation.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityBuilder;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.NullRememberMeServices;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @author dingxigui
 * @version 1.0
 * @date 2021/7/30 17:17
 */
@Component
public class SmsSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

  @Resource
  private SmsAuthenticationSuccessHandler smsAuthenticationSuccessHandler;

  @Resource
  private SmsAuthenticationFailureHandler smsAuthenticationFailureHandler;

  @Override
  public void configure(HttpSecurity httpSecurity) throws Exception {
    SmsAuthenticationProcessingFilter smsAuthenticationProcessingFilter = new SmsAuthenticationProcessingFilter();
    //设置认证管理器，必须与httpSecurity是同一个authenticationManager
    smsAuthenticationProcessingFilter.setAuthenticationManager(httpSecurity.getSharedObject(AuthenticationManager.class));
    //自定义 成功和失败处理器
    smsAuthenticationProcessingFilter.setAuthenticationSuccessHandler(smsAuthenticationSuccessHandler);
    smsAuthenticationProcessingFilter.setAuthenticationFailureHandler(smsAuthenticationFailureHandler);
    // 父过滤器登录成功会调用 rememberMeServices , 默认实现是 NullRememberMeServices
    RememberMeServices rememberMeServices = httpSecurity.getSharedObject(RememberMeServices.class);
    // 指定记住我功能
    smsAuthenticationProcessingFilter.setRememberMeServices(rememberMeServices==null?new NullRememberMeServices():rememberMeServices);
    //添加短信认证过滤器
    httpSecurity.addFilterBefore(smsAuthenticationProcessingFilter,
        UsernamePasswordAuthenticationFilter.class);
  }
}
